package com.haojiang.mh.widget

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import com.haojiang.mh.R
import kotlinx.coroutines.*

/**
 * Created by ZapFive on 2019-05-25.
 *
 *
 * wuzhuang@mirahome.me
 */
class FrameImageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
        AppCompatImageView(context, attrs, defStyleAttr) {

    private var currLevel = 0
    private var intervalCount = 0
    private var intervalJob: Job? = null

    init {
        this.setImageResource(R.drawable.bg_loading_dialog)
    }

    private fun initTimeInterval() {
        cancelInterval()
        intervalJob = GlobalScope.launch {
            while (isActive) {
                delay(50L)
                val level = 1 + intervalCount % 72
                intervalCount++
                if (currLevel == level) return@launch
                currLevel = level
                withContext(Dispatchers.Main) {
                    setImageLevel(level)
                }
            }
        }
    }

    private fun cancelInterval() {
        if (intervalJob != null && !intervalJob!!.isCancelled) {
            intervalJob!!.cancel()
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        initTimeInterval()
    }

    override fun onDetachedFromWindow() {
        cancelInterval()
        super.onDetachedFromWindow()
    }
}
